package com.fare.taluo.core.domain.crawl;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Calendar;
import java.util.List;

import com.dayatang.domain.InstanceFactory;
import com.fare.taluo.core.domain.config.channel.SourceEntity;
import com.fare.taluo.core.domain.config.channel.SourceEntityRepository;
import com.fare.taluo.vo.adapter.AdapterVO;

/**
 * taluo适配器操作的领域模型
 * 包括上传下载修改删除等等
 * 我懒，以vo作为参数传递好了
 * @author guokenye
 *
 */

public class AdapterOperate {
	
	
	
	private AdapterVO vo;
	
	private static final int ADD=1;
	private static final int UPDATE=2;
	private static final int DELETE=3;
	private static final int DOWNLOAD=4;
	private static SourceEntityRepository sorRepsitory = InstanceFactory.getInstance(SourceEntityRepository.class);
	private static AdapterUploadedEntityRepository adapterUploadedEntityRepository = InstanceFactory.getInstance(AdapterUploadedEntityRepository.class);
	private static TaskAdapterEntityRepository adapterRepository = InstanceFactory.getInstance(TaskAdapterEntityRepository.class);
	public AdapterOperate(AdapterVO vo) {
		super();
		this.vo = vo;
	}
	
	/**
	 * 保存一个适配器
	 * @return
	 * @throws Exception
	 */
	public void addAdapter() throws Exception{
		validate(AdapterOperate.ADD);
		//先把class存进去数据库
		AdapterUploadedEntity data=new AdapterUploadedEntity();
		/*data.setFile(vo.getAdapterFile());*/
		data.setClassSize(vo.getAdapterFile().length());
		data.setClassName(vo.getAdapterClassName());
		adapterUploadedEntityRepository.SaveAdapterUploadedEntity(data,vo.getAdapterFile());
		TaskAdapterEntity e=new TaskAdapterEntity();
		SourceEntity sor=sorRepsitory.find(vo.getSourceID());
		e.setSourceId(sor);
		e.setAdapterName(vo.getAdapterClassName());
		e.setAdapterClass(vo.getAdapterClassName());
		e.setIsenable(vo.getIsenable()+"");
		e.setPriority(vo.getPriority()+"");
		Calendar cal=Calendar.getInstance();
		e.setCreattime(cal.getTime());
		e.setUpdatetime(cal.getTime());
		e.setVersion(vo.getVersion());
		e.setRemarks(vo.getRemarks());
		e.setAdapterUploadId(data.getId());
		e.save();
		
		if(vo.getIsenable()==1){//可用,需要关闭其他的
			List<TaskAdapterEntity> other =adapterRepository.findTaskAdapterByConditions(e.getSourceId().getId(), null, null);
			other.remove(e);
			for(TaskAdapterEntity ot:other){
				ot.setIsenable("0");
				ot.save();
			}
		}	
	};
	
	
	/**
	 * 根据条件查询
	 * @return
	 * @throws Exception
	 */
	public List<TaskAdapterEntity> findAdapterByConsdions()throws Exception{
		if(vo==null){
			return adapterRepository.findTaskAdapterByConditions(null, null,null);
		}
		return adapterRepository.findTaskAdapterByConditions(vo.getSourceID(), vo.getIsenable(), vo.getAdapterClassName());
				
	}
	
	/**
	 * 打开或者关闭一个适配器
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public boolean closeOrOpenAdapter()throws Exception{
		validate(UPDATE);
		TaskAdapterEntity adapter=adapterRepository.findTaskAdapterEntity(vo.getId());
		if(adapter==null){
			throw new Exception("has no found adapter as id");
		}
		Calendar cal=Calendar.getInstance();
		if(vo.getIsenable()==1){//可使用
			List<TaskAdapterEntity> other =adapterRepository.findTaskAdapterByConditions(adapter.getSourceId().getId(), null, null);
			other.remove(adapter);
			adapter.setIsenable("1");
			adapter.setUpdatetime(cal.getTime());
			adapter.saveOrUpdateTaskInfoEntity();
			for(TaskAdapterEntity e:other){
				e.setIsenable("0");
				e.setUpdatetime(cal.getTime());
				e.saveOrUpdateTaskInfoEntity();
			}
		}else{
			adapter.setIsenable("0");
			adapter.setUpdatetime(cal.getTime());
			adapter.saveOrUpdateTaskInfoEntity();
		}
		return true;
	}
	
	public boolean deleteAdapter()throws Exception{
		validate(DELETE);
		TaskAdapterEntity adapter=adapterRepository.findTaskAdapterEntity(vo.getId());
		if(adapter==null){
			throw new Exception("has no found adapter as id");
		}
		AdapterUploadedEntity data=adapterUploadedEntityRepository.getById(adapter.getAdapterUploadId());
		adapterRepository.remove(adapter);
		adapterUploadedEntityRepository.removeS(data);
		return true;
	}
	
	
	public AdapterUploadedEntity downloadAdapterFileDataById() throws Exception{
		validate(DOWNLOAD);
		return adapterUploadedEntityRepository.getById(vo.getAdapterUploadId());
	}
	
	
	/**
	 * 验证
	 * @throws Exception 
	 */
	private  void validate(int action) throws Exception{
		
		switch(action){
		case ADD:
			break;
		case UPDATE:
			break;
		case DELETE:
			break;
		case DOWNLOAD:
			
			break;
		default:
			throw new Exception();
		}
	}
	
	
	
	@SuppressWarnings("unused")
	private byte[] fileToByte(File file) throws Exception {
			byte[] result=null;
			FileInputStream fis = null;  
	        ByteArrayOutputStream ops = null;  
	        byte[] temp = new byte[2048];  
	        try {
				fis = new FileInputStream(file);  
				ops = new ByteArrayOutputStream();  
				int n;  
				while ((n = fis.read(temp)) != -1) {  
				    ops.write(temp, 0, n);  
				}  
				result=ops.toByteArray();
				return result;
			} finally{
				temp=null;
				if(ops!=null){
					ops.close();
				}
				if(fis!=null){
					fis.close();
				}
				ops=null;fis=null;
			} 
	}
	
}
